<template>
  <div class="year-month-selector">
    <div class="selector-left">
      <el-tabs v-model="activeMonth" @tab-change="handleMonthChange">
        <el-tab-pane v-for="month in months" :key="month.value" :label="month.label" :name="month.value">
        </el-tab-pane>
      </el-tabs>
    </div>
    <div class="selector-right">
      <el-select v-model="currentYear" @change="handleYearChange" filterable allow-create default-first-option>
        <el-option
          v-for="year in yearOptions"
          :key="year"
          :label="year"
          :value="year"
        />
      </el-select>
    </div>
  </div>
</template>

<script setup>
const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  }
})

const emit = defineEmits(['update:modelValue', 'change'])

const activeMonth = ref('01')
const currentYear = ref('')
const yearOptions = ref([])

// 月份数据
const months = [
  { label: '1月', value: '01' },
  { label: '2月', value: '02' },
  { label: '3月', value: '03' },
  { label: '4月', value: '04' },
  { label: '5月', value: '05' },
  { label: '6月', value: '06' },
  { label: '7月', value: '07' },
  { label: '8月', value: '08' },
  { label: '9月', value: '09' },
  { label: '10月', value: '10' },
  { label: '11月', value: '11' },
  { label: '12月', value: '12' }
]

// 初始化年份选项
function initYearOptions() {
  const currentYear = new Date().getFullYear()
  const years = []
  for (let i = currentYear - 10; i <= currentYear + 10; i++) {
    years.push(i.toString())
  }
  yearOptions.value = years
}

// 监听 modelValue 变化
watch(() => props.modelValue, (newVal) => {
  if (newVal) {
    const [year, month] = newVal.split('-')
    currentYear.value = year
    activeMonth.value = month
  } else {
    // 默认当前年月
    const now = new Date()
    currentYear.value = now.getFullYear().toString()
    activeMonth.value = String(now.getMonth() + 1).padStart(2, '0')
    emitValue()
  }
}, { immediate: true })

// 组件挂载时初始化
onMounted(() => {
  initYearOptions()
  // 如果没有传入默认值，则使用当前年月
  if (!props.modelValue) {
    const now = new Date()
    currentYear.value = now.getFullYear().toString()
    activeMonth.value = String(now.getMonth() + 1).padStart(2, '0')
    emitValue()
  }
})

// 月份变化处理
function handleMonthChange(month) {
  activeMonth.value = month
  emitValue()
}

// 年份变化处理
function handleYearChange() {
  emitValue()
}

// 发送值变化事件
function emitValue() {
  if (currentYear.value && activeMonth.value) {
    const value = `${currentYear.value}-${activeMonth.value}`
    emit('update:modelValue', value)
    emit('change', value)
  }
}
</script>

<style scoped>
.year-month-selector {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 20px;
}

.selector-left {
  flex: 1;
}

.selector-right {
  width: 150px;
}
</style>